Safan Momin Safan Momin - 2 months ago 23
Android Question

call onClick on a button on a different layout

I'm working on a application where I have a list view. The list view has a button which is on different layout file. How can I call the button from my activity? I've tried adding that xml file to my activity but the setOnClickListener doesn't seems to work.

This is how my xml file looks like:

<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="wrap_content">
<LinearLayout
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_centerVertical="true"
android:layout_marginLeft="10dp"
android:layout_marginStart="10dp"
android:orientation="horizontal"
android:padding="20dp">

<EditText
android:id="@+id/objectiveOtherAddedEditText"
android:layout_width="150dp"
android:layout_height="50dp"
android:layout_marginLeft="28dp"
android:ems="10" />

<ImageButton
android:id="@+id/addOtherObjectiveTextBox"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginLeft="5dp"
android:background="@drawable/round_button"
android:src="@android:drawable/ic_input_add"/>

</LinearLayout>




and this is where I want to call it:

public class VisitObjectiveFragment extends Fragment {

public static final String TITLE = "Visit Objective";
SQLiteDatabase database;
SQLiteOpenHelper dbHelper;

public static VisitObjectiveFragment newInstance() {

return new VisitObjectiveFragment();
}

@Nullable
@Override
public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, Bundle savedInstanceState) {

final View view = inflater.inflate(R.layout.fragment_visit_objective, container, false);
final View view1 = inflater.inflate(R.layout.other_objective_list_view, container, false);


ListView listView = (ListView) view.findViewById(R.id.listview_objective);
ImageButton buttonAdd = (ImageButton) view1.findViewById(R.id.addOtherObjectiveTextBox);

buttonAdd.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
Toast.makeText(getActivity(), "Clicked", Toast.LENGTH_SHORT).show();
}
});

return view;
}


}

S A S A
Answer Source

Put setOnClickListener(new View.OnClickListener() {} inside your adapter class. If you don`t have one. Create it