2013-10-23 2 views
1

완벽하게 작동하는 안드로이드 응용 프로그램에 ListActivity가 있습니다. 가속도계를 사용하여 스크롤 기능을 추가하기 전까지. 내가 상승 운동을 할 때가속도계 문제가있는 안드로이드 목록 이동

package be.pxl.minecraftguide; 

import android.app.ListActivity; 
import android.content.ContentResolver; 
import android.database.Cursor; 
import android.hardware.Sensor; 
import android.hardware.SensorEvent; 
import android.hardware.SensorEventListener; 
import android.hardware.SensorManager; 
import android.os.Bundle; 
import android.support.v4.widget.SimpleCursorAdapter; 
import android.widget.ListView; 
import be.pxl.minecraftguide.providers.RecipeCategoryProvider; 

public class Crafting extends ListActivity implements SensorEventListener { 
    private SimpleCursorAdapter adapter; 
    private SensorManager sensorManager; 
    private Sensor acceleroMeter; 
    private float[] history = new float[2]; 

    @Override 
    protected void onCreate(Bundle savedInstanceState) { 
     // TODO Auto-generated method stub 
     super.onCreate(savedInstanceState);  
     setContentView(R.layout.categorylist); 

     ContentResolver cr = getContentResolver(); 
     Cursor cursor = cr.query(RecipeCategoryProvider.CONTENT_URI, null, null, null, null); 
     String[] from = {RecipeCategoryProvider.COL_CATID, RecipeCategoryProvider.COL_CATIMG, RecipeCategoryProvider.COL_CATDESC}; 
     int[] to = { R.id.txtCatID, R.id.imgCatImage, R.id.txtCatDescription }; 
     adapter = new SimpleCursorAdapter(getApplicationContext(), R.layout.categoryrow, cursor, from, to, 0); 
     /*SimpleCursorAdapter.ViewBinder viewBinder = new SimpleCursorAdapter.ViewBinder() { 

      @Override 
      public boolean setViewValue(View view, Cursor cursor, int arg2) { 
       if(view.getId() == R.id.imgCatImage) { 
        ImageView image = (ImageView)findViewById(R.id.imgCatImage); 
        image.setImageResource(R.drawable.ic_launcher); 
       } 

       return false; 
      } 

     };*/ 

     setListAdapter(adapter); 

     //__________BRON/ http://stackoverflow.com/questions/18751878/android-using-the-accelerometer-to-create-a-simple-maraca-app_____________ 

     sensorManager = (SensorManager) getSystemService(SENSOR_SERVICE); 
     acceleroMeter = sensorManager.getDefaultSensor(Sensor.TYPE_ACCELEROMETER); 
     sensorManager.registerListener(this, acceleroMeter, 1000000); 

     /*recipeListView.setOnClickListener(new OnItemClickListener(){ 
      public void onItemClick(AdapterView<?> parent, View row, 
        int position, long id) { 

        TextView txtId = (TextView)row.findViewById(R.id.txtRecipeID); 
        int recipeID = Integer.parseInt(txtId.getText().toString()); 
        String description = ((TextView)row.findViewById(R.id.txtRecipeDescription)).getText().toString(); 


        // Launching new Activity on selecting single List Item 
        // Intent craftingDetailIntent = new Intent(getApplicationContext(), craftingdetail.class); 
        // sending data to new activity 
        //craftingDetailIntent.putExtra("Category", item); 
        //startActivity(craftingDetailIntent); 
       } 
     });*/ 
    } 

    /*@Override 
    protected void onListItemClick(ListView l, View v, int position, long id) { 
     // TODO Auto-generated method stub 
     super.onListItemClick(l, v, position, id); 

     int recipeID = Integer.parseInt(v.getTag().toString()); 
    }*/ 

    @Override 
    protected void onPause() { 
     // TODO Auto-generated method stub 
     super.onPause(); 
     sensorManager.unregisterListener(this); //De accelerometer afzetten 
    } 

    @Override 
    protected void onResume() { 
     // TODO Auto-generated method stub 
     super.onResume(); 
     sensorManager.registerListener(this, acceleroMeter, SensorManager.SENSOR_DELAY_UI); //De accelerometer opnieuw starten 
    } 

    @Override 
    public void onAccuracyChanged(Sensor sensor, int accuracy) { 
     // TODO Auto-generated method stub 

    } 

    @Override 
    public void onSensorChanged(SensorEvent event) { 
     if (event.sensor.getType() == Sensor.TYPE_ACCELEROMETER) { 
      float xChange = history[0] - event.values[0]; 
      float yChange = history[1] - event.values[1]; //Verschil tussen nieuwe en oude positie ophalen. 

      history[0] = event.values[0]; 
      history[1] = event.values[1]; //Nieuwe waarden bewaren voor volgende event trigger 

      if (xChange > 2){ 
       //Links 
      } 
      else if (xChange < -2){ 
       //Rechts 
      } 

      if (yChange > 2){ 
        getListView().smoothScrollBy(getListView().getHeight() * adapter.getCount(), 2000); 
        getListView().postDelayed(new Runnable() { 
         @Override 
         public void run() { 
          getListView().smoothScrollBy(0, 0); //Geanimeerd scrollen naar laatste positie 
          getListView().setSelection(adapter.getCount() - 1); 
         } 
        }, 1000); 
      } 
      else if (yChange < -2){ 
       getListView().smoothScrollBy(getListView().getHeight() * adapter.getCount(), 2000); 
       getListView().postDelayed(new Runnable() { 
        @Override 
        public void run() { 
         getListView().smoothScrollBy(0, 0); //Geanimeerd scrollen naar eerste positie positie 
         getListView().setSelection(0); 
        } 
       }, 1000); 
      } 
     } 

    } 


} 

문제는, 목록 하단에 광고 숙박을 아래로 스크롤해야합니다

여기 내 코드입니다. 하지만 내 목록이 아래로 스크롤 된 다음 가끔씩 백업됩니다. 하향 움직임에 대해서도 동일합니다.

<?xml version="1.0" encoding="utf-8"?> 
<ListView xmlns:android="http://schemas.android.com/apk/res/android" 
    android:id="@android:id/list" 
    android:layout_width="match_parent" 
    android:layout_height="wrap_content" 
    android:background="@drawable/minecraft_portrait" 
    android:transcriptMode="alwaysScroll" > 


</ListView> 

그리고 정말 관련이없는 , 그러나 여기가

<?xml version="1.0" encoding="utf-8"?> 
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android" 
    android:id="@+id/recipeRow" 
    android:layout_width="match_parent" 
    android:layout_height="65sp" 
    android:background="@drawable/listview_selector" > 

    <TextView 
     android:id="@+id/txtCatID" 
     android:layout_width="wrap_content" 
     android:layout_height="wrap_content" 
     android:layout_marginLeft="5dp" 
     android:layout_marginTop="5dp" 
     android:textColor="@android:color/black" /> 

    <ImageView 
     android:id="@+id/imgCatImage" 
     android:layout_width="wrap_content" 
     android:layout_height="55sp" 
     android:layout_centerVertical="true" 
     android:layout_alignParentLeft="true" 
     android:src="@drawable/ic_launcher" 
     android:contentDescription="@string/recipecategory" /> 

    <TextView 
     android:id="@+id/txtCatDescription" 
     android:layout_width="fill_parent" 
     android:layout_height="wrap_content" 
     android:layout_centerVertical="true" 
     android:layout_toRightOf="@id/imgCatImage" 
     android:gravity="center" 
     android:background="#99FFFFFF" 
     android:textSize="20sp" 
     android:textColor="@android:color/black" 
     android:text="test" /> 

</RelativeLayout> 

가 어떻게이 문제를 해결할 수 있습니다 내 행 XML입니까?

답변

2

나는 (구글 유리의 맥락에서) 센서를 사용하여 ListActivity 스크롤에 대해 동일한 솔루션을 찾고있었습니다, 다른 대답은 나를 위해 작동하지 않았다 (불규칙적이었다 스크롤).

그래도 ListView (아래 예에서는 mList)을 기반으로 한 다른 버전을 사용할 수있었습니다. 이는 또한 모든 글래스 디스플레이가 동일한 크기이므로 한 번에 화면에 고정 된 수의 항목을 가정하지만, 좀 더 일반적인 안드로이드 솔루션을 위해 화면에 얼마나 많은 항목이 있는지 확인할 수 있습니다. 이 솔루션은 지원되는 장치에서 일부 센서 융합을 수행하는 Sensor.TYPE_ROTATION_VECTOR도 사용하므로 출력이 낮아 원치 않는 위/아래 움직임이 발생하지 않습니다.

리스너 등록

mSensorManager = (SensorManager) mContext.getSystemService(Context.SENSOR_SERVICE); 
    mSensorManager.registerListener(this, 
     mSensorManager.getDefaultSensor(Sensor.TYPE_ROTATION_VECTOR), 
     SensorManager.SENSOR_DELAY_UI); 

을 ... 그리고 여기에 onSensorChanged() 방법입니다 :

@Override 
public void onSensorChanged(SensorEvent event) { 
    if (mList == null) { 
     return; 
    } 

    if (event.sensor.getType() == Sensor.TYPE_ROTATION_VECTOR) { 
     SensorManager.getRotationMatrixFromVector(mRotationMatrix, event.values); 

     // Only uncomment the below two lines if you're running on Google Glass 
     //SensorManager.remapCoordinateSystem(mRotationMatrix, SensorManager.AXIS_X, 
     // SensorManager.AXIS_Z, mRotationMatrix); 
     SensorManager.getOrientation(mRotationMatrix, mOrientation); 

     mHeading = (float) Math.toDegrees(mOrientation[0]); 
     mPitch = (float) Math.toDegrees(mOrientation[1]); 

     float xDelta = history[0] - mHeading; // Currently unused 
     float yDelta = history[1] - mPitch; 

     history[0] = mHeading; 
     history[1] = mPitch; 

     float Y_DELTA_THRESHOLD = 0.10f; 

     //Log.d(TAG, "Y Delta = " + yDelta); 

     int scrollHeight = mList.getHeight() 
      /19; // 4 items per page, scroll almost 1/5 an item 

     //Log.d(TAG, "ScrollHeight = " + scrollHeight); 

     if (yDelta > Y_DELTA_THRESHOLD) { 
      //Log.d(TAG, "Detected change in pitch up..."); 
      mList.smoothScrollBy(-scrollHeight, 0); 
     } else if (yDelta < -Y_DELTA_THRESHOLD) { 
      //Log.d(TAG, "Detected change in pitch down..."); 
      mList.smoothScrollBy(scrollHeight, 0); 
     } 
    } 
} 

추가 세부 사항이 응답에 : 코드에 대한 https://stackoverflow.com/a/23298377/937715

센서를 다시 매핑 그 좌표계를 사용하여 Android 기기의 모든 방향 변경 사항을 처리 할 수 ​​있습니다 (참조). 0 https://stackoverflow.com/a/22138449/937715

+2

이 링크는 질문에 대한 답변 일지 모르지만 여기에 답변의 핵심 부분을 포함하고 참조 용 링크를 제공하는 것이 좋습니다. 링크 된 페이지가 변경되면 링크 전용 답변이 유효하지 않게 될 수 있습니다. – h22

+0

@ AudriusMeškauskas 감사합니다. 방금 필수 부품을 인라인으로 업데이트했습니다. –

+1

안녕하세요, 선생님, 여기에 더 깨끗한 해결책이 있다는 것을 알았습니다. 내 더러운 솔루션이 제대로 작동했지만 이상적이지 않았습니다! 비슷한 문제가있는 사람들이 귀하의 솔루션이 그만한 가치가 있다고 생각합니다. – DerpyNerd

0

좋아, 며칠 전에이 문제를 해결했습니다.

다른 사람이이 문제가 발생하면 Y 축의 변경을 늘리는 것이 좋습니다.

if (yChange > 12){ 
     listView.smoothScrollBy(listView.getHeight() * adaptor.getCount(), 1000); 
     listView.postDelayed(new Runnable() { 
      @Override 
      public void run() { 
       listView.smoothScrollBy(0, 0); //Geanimeerd scrollen naar laatste positie 
       listView.setSelection(adaptor.getCount() - 1); 
      } 
     }, 500); 
} 
else if (yChange < -12){ 
    listView.smoothScrollBy(listView.getHeight() * adaptor.getCount(), 1000); 
    listView.postDelayed(new Runnable() { 
     @Override 
     public void run() { 
      listView.smoothScrollBy(0, 0); //Geanimeerd scrollen naar eerste positie positie 
      listView.setSelection(0); 
     } 
    }, 500); 
} 
관련 문제