2014-12-06 149 views
0

我已经创建了一个动态按钮并将其添加到LinearLayout中,Linear layout的父视图是Horizo​​ntalScrollView。 我需要动态滚动Horozontal scollview的滚动位置。在屏幕上获取按钮位置

我无法获得屏幕上的按钮位置。它总是给屏幕上的按钮Y和Y位置[0,0]。

我的XML文件:

<HorizontalScrollView 
      android:id="@+id/horizontalScrollView1" 
      android:layout_width="wrap_content" 
      android:layout_height="fill_parent" 
      android:layout_above="@id/imv_Line_Invisibe" 
      android:layout_marginLeft="15dp" 
      android:layout_toRightOf="@id/imv_logo" 
      android:scrollbars="none" > 

      <LinearLayout 
       android:id="@+id/lay_but" 
       android:layout_width="wrap_content" 
       android:layout_height="fill_parent" 
       android:orientation="horizontal" > 
      </LinearLayout> 

</HorizontalScrollView> 

添加按钮,动态线性布局:

int i = 0; 
    for (HashMap<String, String> map : category) 
     for (Entry<String, String> mapEntry : map.entrySet()) { 
      String strButLabel = mapEntry.getValue(); 
      Log.i("map", "" + strButLabel); 
      LinearLayout.LayoutParams params = new LinearLayout.LayoutParams(LayoutParams.WRAP_CONTENT, LayoutParams.MATCH_PARENT); 
      params.weight = 1.0f; 
      String value = mapEntry.getValue(); 
      TextView tvSetID = new TextView(this); 
      tvSetID.setId(i); 
      butCategory = new Button(this); 
      butCategory.setId(i); 
      butCategory.setText(value); 
      butCategory.setTextSize(13); 
      butCategory.setAllCaps(true); 
      butCategory.setLayoutParams(params); 
      butCategory.setTypeface(custom_font, Typeface.BOLD); 
      butCategory.setGravity(Gravity.CENTER | Gravity.BOTTOM); 
      butCategory.setPadding(0, 0, 20, 20); 
      butCategory.setBackgroundResource(R.drawable.nav_phone_unselect); 
      butCategory.setTextColor(Color.parseColor("#666666")); 
      butCategory.setOnClickListener(OnClickChangeButtonColor(butCategory)); 
      i++; 
     } 

这是我使用的用于获取屏幕上的按钮位置的代码:

int temp_index = intent.getIntExtra("btn_index_value", 0); 
Button butCategory = (Button) findViewById(temp_index); 
butCategory.setBackgroundResource(R.drawable.nav_phone_select); 
butCategory.setTextColor(Color.parseColor("#FFFFFF")); 
String i1 = butCategory.getText().toString(); 
int[] locations = new int[2]; 
butCategory.getLocationOnScreen(locations); 
int x = locations[0]; 
int y = locations[1]; 
horizontal_Category.scrollTo(x, y); 
index = temp_index; 
+1

您可以使用View.getX()&View.getY()来获取像素的x和y坐标。 – Muthu 2014-12-06 12:13:23

回答

0

您可以使用this - View.getLocationOnScreen()和/或getLocationInWindow()。