skip to Main Content

Mainactivity.java

public class MainActivity extends AppCompatActivity {

    private RecyclerView mRecyclerView;

    private WordAdapter mAdapter;

    private RecyclerView.LayoutManager mLayoutManager;
    private ArrayList<WordClass> mWordList;

    private EditText mEditText1, mEditText2;
    private Button mInseartButton, mRemoveButton;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        mEditText1 = findViewById(R.id.insert_text);
        mEditText2 = findViewById(R.id.remove_text);
        mInseartButton = findViewById(R.id.insert_button);
        mRemoveButton = findViewById(R.id.remove_button);

        CreateArrayList();

        buildRecyclerView();

        mInseartButton.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                int position = Integer.parseInt(mEditText1.getText().toString());
                insertValues(position);
            }
        });

        mRemoveButton.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                int position = Integer.parseInt(mEditText2.getText().toString());
                removeValues(position);
            }
        });
    }

    public void CreateArrayList() {
        mWordList = new ArrayList<>();

        mWordList.add(new WordClass(R.drawable.ic_face, "Text1", "Text2"));
        mWordList.add(new WordClass(R.drawable.ic_face, "Text1", "Text2"));
        mWordList.add(new WordClass(R.drawable.ic_face, "Text1", "Text2"));

    }

    public void buildRecyclerView() {
        mRecyclerView = findViewById(R.id.recycler_view);
        mLayoutManager = new LinearLayoutManager(this);
        mAdapter = new WordAdapter(mWordList);
        mRecyclerView.setHasFixedSize(true);
        mRecyclerView.setLayoutManager(mLayoutManager);
        mRecyclerView.setAdapter(mAdapter);

        mAdapter.setOnItemClickListener(new WordAdapter.OnItemClickListener() {
            @Override
            public void onItemClick(int posistion) {
                String list1Text = mWordList.get(posistion).getmTextView1();
                Intent i = new Intent(MainActivity.this, DetailActivity.class);
                i.putExtra("name", list1Text);
                startActivity(i);
            }
        });
    }

    public void insertValues(int position) {
        mWordList.add(position, new WordClass(R.drawable.ic_face, "insert new item in index: " + position, "Text2"));
        mAdapter.notifyItemInserted(position);
    }

    public void removeValues(int position) {
        mWordList.remove(position);
        mAdapter.notifyItemRemoved(position);
    }
}

اترك تعليقاً

لن يتم نشر عنوان بريدك الإلكتروني. الحقول الإلزامية مشار إليها بـ *