I am facing a problem on dynamically created Layout on a fragment. Here is my Fragment code
public class Points extends Fragment {
LinearLayout gameListHolder;
String name;
@Nullable
@Override
public View onCreateView(@NonNull LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
return inflater.inflate(R.layout.fragment_game,null);
}
@Override
public void onViewCreated(@NonNull View view, @Nullable Bundle savedInstanceState) {
gameListHolder=view.findViewById(R.id.gameListHolder);
for(int i=0;i<=3;i++){
LayoutInflater layoutInflater = (LayoutInflater)getActivity().getBaseContext().getSystemService(Context.LAYOUT_INFLATER_SERVICE);
final View addView = layoutInflater.inflate(R.layout.game_list_single, null);
name=Integer.toString(i);
Button status= (Button) addView.findViewById(R.id.statusButton);
status.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
Log.i("Rahat",name);
}
});
gameListHolder.addView(addView);
}
}
}
My Problem is, when I click on the status button it always gives me the value of last index in my case 3. I want it to be when i clilck the first button it will give me the value of first index, then for second it will give me value of 2nd index.
请使用本地“名称”变量,如下所示:
String name=Integer.toString(i);
You have the option to set tag to your button and then in onclick you can check the tag to find which button is clicked. ie
item.setTag(name);
status.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
Log.i("Rahat",view.getTag().toString());
}
});
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.