Laboratoriyaning amaliy qismi
Agar standart holatda biz XML faylni setContentView(R.layout.activity_main) usuliga qo‘shsak, uni dasturiy jihatdan yaratishda bizga bu usul kerak bo‘lmaydi. Uni o‘chiring va kodni yozing:
paket en.alexanderkimov.test;
android.app.Activity import;
android.content.Context import;
android.content.Intent import;
android.os.Bundle import;
android.view.View import;
android.view.View.OnClickListenerni import qilish;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.LinearLayout.LayoutParams;
android.widget.TextView import;
import android.widget.Toast;
umumiy sinf TestActivity faollikni kengaytiradi {
/** Faoliyat birinchi marta yaratilganda chaqiriladi. */
@Override
public void onCreate (to‘plam savedInstanceState) {
super.onCreate(savedInstanceState);
// bizga bu usul kerak emas
// setContentView(R.layout.activity_test);
LinearLayout layout = yangi LinearLayout(TestActivity.this);
layout.setId(R.id.layout_id);
LayoutParams layoutParams = yangi LayoutParams(LayoutParams.MATCH_PARENT,
LayoutParams.MATCH_PARENT);
layout.setLayoutParams(layoutParams);
layout.setOrientation(LinearLayout.VERTICAL);
ImageView imageView = new ImageView(TestActivity.this);
imageView.setId(R.id.image_id);
imageView.setImageResource(R.drawable.ic_launcher);
LayoutParams imageViewLayoutParams = yangi LayoutParams(
LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT);
imageView.setLayoutParams(imageViewLayoutParams);
layout.addView (imageView);
setContentView (tartib);
layout.setOnClickListener(onViewClickListener);
imageView.setOnClickListener(onViewClickListener);
}
onClickListener onViewClickListener = yangi OnClickListener() {
@Override
public void onClick(View v) {
int myId = v.getId();
Toast.makeText(TestActivity.this,
"ID: " + String.valueOf(myId) + " bosildi",
Toast.LENGTH_LONG).show();
}
};
}
Shakllanish printsipi quyidagicha - biz LinearLayout ob'ektini (yoki boshqa konteyner) yaratamiz va kerakli xususiyatlarni o‘rnatamiz. Keyinchalik, biz kerakli bolalar elementlarini yaratamiz va ularning xususiyatlarini o‘rnatamiz. AddView() usuli orqali bola elementni asosiy elementga ulashni unutmang.
Dostları ilə paylaş: |