How's Layout sending id to Main_activity?



  • Hello, everyone. Please don't kick hard. I'm just learning. I want to hang a listener on id in MainActivity. Two codes:

    bottom_sheet_layuot.xml 
    

    <LinearLayout
    android:layout_width="match_parent"
    android:layout_height="55dp"
    android:id="@+id/share"
    android:orientation="horizontal"
    >

    and MainActivity

    class MainActivity : AppCompatActivity() {

    private lateinit var dialog_btn: Button
    private lateinit var share: View

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_main)
    
      val bottomSheetDialog = BottomSheetDialog(this)
    
      val view = layoutInflater.inflate(R.layout.bottom_sheet_layuot, null)
    
        dialog_btn = findViewById&lt;Button&gt;(R.id.dialog_btn);
        share = findViewById&lt;View&gt;(R.id.share);
    
        bottomSheetDialog.setContentView(view)
    
        dialog_btn.setOnClickListener {
           bottomSheetDialog.show()
        }
    
           share.setOnClickListener {
                Toast.makeText(this, "Share",Toast.LENGTH_SHORT).show()
            }
       }
    

    }



  • If you understand correctly, you want a linerLayout from xml on id in MainActivity. Let's eat in activiy_main.xml ListView

    <ListView
            android:id="@+id/listView"
            android:layout_width="0dp"
            android:layout_height="0dp"
            app:layout_constraintBottom_toBottomOf="parent"
            app:layout_constraintEnd_toEndOf="parent">
    

    To get it in MainActivity, you have to set up the main site of the ListView and put it on the id, so...

    public class MainActivity extends AppCompatActivity {
        private ListView listView; //создаем 
    
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
         //... 
         listView = findViewById(R.id.listView); //присваиваем и можем дальше обращаться к listView
    
         //например, сделаем событие по элементу списка 
         listView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
          @Override
          public void onItemClick(AdapterView&lt;?&gt; parent, View view, int position, long id) {
            }
        });
    

    }
    }

    R.id.listView is the id that is indicated in xml, as can be done with all elements.



Suggested Topics

  • 2
  • 2
  • 2
  • 2
  • 2
  • 2
  • 2
  • 2
  • 2
  • 2
  • 2
  • 2
  • 2
  • 2
  • 2