简体   繁体   English

编写android代码时此处理程序的用途是什么?

[英]what is the use of this handler while writing android code?

Here in the below code a songsManager object is created and then why is this.songsList used to store the song files and why not only songsList is used. 在下面的代码中,将创建一个songsManager对象,然后为什么使用this.songsList来存储歌曲文件,以及为什么不只使用songsList。 Main question is what is the use of this and what exactly is it and when it is used? 主要的问题是它的用途是什么,它的确切用途以及何时使用? My main doubt is that here since no other songsList is declared so there is no chance of songsList clashing so why to specifically refer to it as the songsList declared in the present class. 我的主要疑问是,由于这里没有声明其他songsList,所以没有songsList冲突的可能性,因此为什么要专门将其称为当前类中声明的songsList。 Mainly I use it when there are arguments passed to a function whose names are same as that of objects or variables declared within the class so to avoid confusion and to tell the compiler that I want to use the object declared in that class and not the one passed as an argument I used this.. Please correct me if I am wrong and add to my knowledge about this. 主要是在有参数传递给函数的名称与该类中声明的对象或变量的名称相同的函数时使用它,以避免混淆并告诉编译器我要使用该类中声明的对象,而不是一个作为参数传递给我,我曾经用过这个。

The code lines of interest are followed by // please see to it 感兴趣的代码行后跟// //请注意

public class CustomizedListView extends Activity{

private int currentIndex;
private String[] menuItems = {"Play","Share Music Via","Details"};
private LinkedList<File> songsList = new LinkedList<File>();//
private ArrayList<HashMap<String, String>> songsListdata = new ArrayList<HashMap<String, String>>();
private MediaMetadataRetriever mmr = new MediaMetadataRetriever();
private Utilities utils=new Utilities();
ListView list=null;
ModifiedAdapter adapter=null;
SongsManager plm=null;//
Button search;
@Override
public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.playlist);

    plm = new SongsManager();//
    File extStore = Environment.getExternalStorageDirectory();
    // get all songs from sdcard
    this.songsList = plm.getFilesInFolder(extStore);//
    for (int i = 0; i < songsList.size(); i++) {
        // creating new HashMap
        HashMap<String, String> song = new HashMap<String, String>();
        mmr.setDataSource(songsList.get(i).getAbsolutePath().toString());

        //getting artist
        String artist = mmr.extractMetadata(MediaMetadataRetriever.METADATA_KEY_ALBUMARTIST);
        if(artist==null)
            artist=mmr.extractMetadata(MediaMetadataRetriever.METADATA_KEY_ARTIST);

        //getting Duration
        String len = mmr.extractMetadata(MediaMetadataRetriever.METADATA_KEY_DURATION);

        long Len=0;
        try
        {
            Len=Integer.parseInt(len);
        }
        catch(Exception e)
        {
            Log.i(null, ":conversion error");
        }
        len=utils.milliSecondsToTimer(Len);
        Log.i(null, "length"+len);
        song.put("songTitle", (songsList.get(i)).getName().substring(0, ((songsList.get(i)).getName().length() - 4)));
        song.put("songArtist", artist);
        song.put("duration", len);
        song.put("songPath",songsList.get(i).getAbsolutePath().toString());
        // adding HashList to ArrayList
        songsListdata.add(song);
    }

    list=(ListView)findViewById(R.id.list);
    // Getting adapter by passing xml data ArrayList
    adapter=new ModifiedAdapter(this, songsListdata);
    list.setAdapter(adapter);
    // Click event for single list row
    list.setOnItemClickListener(new OnItemClickListener() {
        @Override
        public void onItemClick(AdapterView<?> parent, View view,
                final int position, long id) {

            final String songPath =songsList.get(position).getAbsolutePath().toString();
            AlertDialog.Builder builder = new AlertDialog.Builder(CustomizedListView.this);
            builder.setTitle((songsList.get(position)).getName().substring(0, ((songsList.get(position)).getName().length() - 4)));
            builder.setItems(menuItems, new DialogInterface.OnClickListener()
             {

                    public void onClick(DialogInterface dialog, int item)
                    {  

                        if(item==0)
                        {
                            Intent in = new Intent(getApplicationContext(),MainActivity.class);
                            // Sending songIndex to PlayerActivity
                            in.putExtra("songIndex", position);
                            setResult(100, in);
                            // Closing PlayListView
                            finish();
                        }
                        else if(item==2)
                        {
                            Intent details = new Intent(getApplicationContext(),Details.class);
                            details.putExtra("songPath", songPath);
                            startActivity(details);
                        }
                        else if(item==1)
                        {
                            Intent intent = new Intent();  
                            intent.setAction(Intent.ACTION_SEND);  
                            intent.setType("audio/*");
                            intent.putExtra(Intent.EXTRA_STREAM, Uri.fromFile(new File(songPath)));
                            startActivity(intent);
                        }
                    }
             });
            AlertDialog alert = builder.create();
            alert.show();
        }
    });

    //Search for a song implementations
    search=(Button)findViewById(R.id.searchForSong);
    search.setOnClickListener(new OnClickListener() {

        @Override
        public void onClick(View arg0) {
            // TODO Auto-generated method stub
            Intent launchBrowser=new Intent(getApplicationContext(), Browser.class);
            startActivity(launchBrowser);
        }
    });
}

} }

this keyword is used to refere to the current object 此关键字用于引用当前对象

So you can access any member of current object using this.member. 因此,您可以使用this.member访问当前对象的任何成员。 As in your example you are accesig songList within the current object so there is no difference between using this and not using this. 就像您的示例一样,您在当前对象中使用accesig songList,因此使用它和不使用它之间没有区别。

More use of this keyword 更多使用此关键字

as you mentioned about the following example 正如您提到的以下示例

private int a;
void method(int a){
    this.a = a;
}

here this is used to refer to the member of current object as the names are same. 由于名称相同,此处用于引用当前对象的成员。 if you used 如果你用过

void method(int b){
    a = b;
}

then there would be no difference between using this and not using this 那么使用和不使用之间没有区别

Some More Example 更多例子

private int a = 5;

public void method() {
    int a = 6;
    System.out.println(a); // will print 6 
    System.out.println(this.a);  // will print 5
}

int the following example the second one is pointing to the member variable of current object so it is printing 5. 在以下示例中,第二个示例指向当前对象的成员变量,因此它正在打印5。

Actually this answer should be broken in a few steps 实际上,这个答案应该分几步来解决

1 1

THIS operator 该运营商

it will refer to the current object/scope in which it is used 它将引用使用它的当前对象/范围

for eg: say a button listener is made like this 例如:说一个按钮监听器是这样制作的

new button(context).setOnClickListener(new View.onClickListener(public void onClick(View v){ //Using this here to refers to this onclicklistener new button(context).setOnClickListener(new View.onClickListener(public void onClick(View v){){//在此使用表示此onclicklistener

}); });

// for a constructor //对于构造函数

public classname(int arg1){ //so to initialise the arg1 of yur class with this arg1 public classname(int arg1){//因此使用此arg1初始化yur类的arg1

//for just thesake of.clarity you write this.arg1=arg1; //仅出于声明的目的,您可以编写以下代码:arg1 = arg1;

} }

2 2

this used here with the songlist is redundant and is of no signficance as ther e is no conflict. 这与歌曲列表一起使用是多余的,并且没有意义,因为这没有冲突。

Hope this helps you. 希望这对您有所帮助。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM