kotlin编《第一行代码》

Posted 霞腾龙升

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了kotlin编《第一行代码》相关的知识,希望对你有一定的参考价值。

一、alertdialog

java:

  AlertDialog.Builder dialog=new AlertDialog.Builder(MainActivity.this);

  dialog.setTitle("This is Dialog");

  dialog.setMessage("Something important.");

  dialog.setCancelable(false);

  dialog.setPositiveButton("OK",new DialogInterface.OnClickListener(){

    public void onClick(DialogInterface dialog,int which){

    }

  });

  dialog.setNegativeButton("Cancel",new DialogInterface.OnclickListener(){

    public void onClick(DialogInterface diailog,int which){

    }

  });

  dialog.show();

kotlin:

fun alert(v:View?){
  val dialog1=AlertDialog.Builder(this)
  dialog1.setTitle("This is Dialog")
  dialog1.setMessage("Something important.")
  dialog1.setCancelable(false)
  dialog1.create().show()
}

二、listview

java:

  <ListView
    android:id="@+id/list_view"
    android:layout_width="match_parent"
    android:layout_height="match_parent"

  />

  private String[] data={"Apple","Banana","Orange","Watermelon","Pear","Grape","Pineapple",
    "Strawberry","Cherry","Mango","Apple","Banana","Orange","Watermelon",
    "Pear","Grape","Pineapple","Strawberry","Cherry","Mango"};
  @Override
  protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);
    ArrayAdapter<String> adapter=new ArrayAdapter<String>(
    MainActivity.this,R.layout.abc_action_menu_item_layout,data);
    ListView listView=(ListView)findViewById(R.id.list_view);
    listView.setAdapter(adapter);
  }

kotlin:

  private val data = arrayOf("Apple", "Banana", "Orange", "Watermelon", "Pear", "Grape", "Pineapple",

     "Strawberry", "Cherry", "Mango", "Apple", "Banana", "Orange", "Watermelon",

    "Pear", "Grape", "Pineapple", "Strawberry", "Cherry", "Mango")
  override fun onCreate(savedInstanceState: Bundle?) {
  val adapter = ArrayAdapter(
    [email protected], R.layout.abc_action_menu_item_layout, data)
  listView.adapter = adapter

}

 

 

 

以上是关于kotlin编《第一行代码》的主要内容,如果未能解决你的问题,请参考以下文章

用kotlin方式打开《第一行代码:Android》

Kotlin实现《第一行代码》案例“酷欧天气”

Kotlin 延迟初始化和密封类[第一行代码 Kotlin 学习笔记]

Kotlin 扩展函数和运算符重载[第一行代码 Kotlin 学习笔记]

kotlin-从一个片段更改多个片段的小数位

《第一行代码》 第三版 - 第二章(笔记)