Can't create surfaceView in a fragment - java

Could someone help me to create SurfaceView in a fragment? Below is my code. It always stops at thr line: if (!surfaceHolder.getSurface().isValid()) and I don't know why.
Fragment code:
<pre>
public class FirstActivity extends Fragment/* implements OnTouchListener*/ {
CameraView cameraView;
#Override
public void onActivityCreated(Bundle savedInstanceState) {
// TODO Auto-generated method stub
super.onCreate(savedInstanceState);
/* instantiating the surface view */
cameraView = new CameraView(this.getActivity());
/* setting the listener - this, because it is defined within the activity */
// cameraView.setOnTouchListener(this);
}
// public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
// View v = inflater.inflate(R.layout.lin, null);
//
// cameraView = (CameraView) v.findViewById(R.id.cameraView);
//
// return v;
//
// }
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
return new CameraView(getActivity());
}
// #Override
// public boolean onTouch(View arg0, MotionEvent arg1) {
// // TODO Auto-generated method stub
// return false;
// }
#Override
public void onStart() {
super.onStart();
}
#Override
public void onResume() {
super.onResume();
cameraView.onResumeCameraView();
}
#Override
public void onPause() {
super.onPause();
cameraView.onPauseCameraView();
}
}
</pre>
CameraView code:
<pre>
public class CameraView extends SurfaceView implements Runnable {
Thread thread = null;
SurfaceHolder surfaceHolder;
private Paint paint = new Paint(Paint.ANTI_ALIAS_FLAG);
Bitmap bitmap;
int WIDTH = 320;
int HEIGHT = 240;
volatile boolean running = false;
public CameraView(Context context) {
super(context);
// TODO Auto-generated constructor stub
surfaceHolder = getHolder();
bitmap = Bitmap.createBitmap(WIDTH, HEIGHT, Bitmap.Config.ARGB_8888/*Bitmap.Config.ALPHA_8*//*Bitmap.Config.RGB_565*/);
Log.d("S3", "stworzono bitmape");
}
public void onResumeCameraView() {
running = true;
thread = new Thread(this);
thread.start();
}
public void onPauseCameraView() {
boolean retry = true;
running = false;
while (retry) {
try {
thread.join();
retry = false;
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
#Override
public void run() {
// TODO Auto-generated method stub
while (running) {
if (!surfaceHolder.getSurface().isValid()) {
Log.d("S3", "blad");
continue;
}
Log.d("S3", "dalej");
Canvas canvas = surfaceHolder.lockCanvas();
canvas.drawColor(Color.WHITE);
paint.setColor(Color.RED);
canvas.drawRect(0, 0, 100, 100, paint);
surfaceHolder.unlockCanvasAndPost(canvas);
}
}
}
</pre>
Thank You for help.

Use SurfaceHolder.addCallback() to register a callback interface. It will notify you when the surface to available, destroyed and when it changes.

My onCreateView function looks:
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
RelativeLayout relativeLayout = new RelativeLayout(this.getActivity());
TextView textView = new TextView(this.getActivity());
textView.setText("Simply dummy text");
relativeLayout.addView(textView);
relativeLayout.addView(cameraView);
return relativeLayout;
}
I can create and add textView without any problems. But if I'm trying to add cameraView the application crashes. Why? I'm creating cameraView in function onActivityCreated

I don't see any code in your post that either references a SurfaceView declared in XML or adds the SurfaceView programmatically to the layout. You need to do either of those, or the SurfaceView can't be drawn.
To add progammatically, in onCreateView(...), do:
mCameraView = new CameraView(...);
ViewGroup myRootLayout = (ViewGroup)findViewById(...)
myRootLayout.addView(mCameraView);

Related

Why is my fragment *sometimes* blank when I return to it via NavController.navigateUp()?

When returning to IpFragment via navigateUp() it sometimes is blank, when it should be showing a couple simple textviews. Sometimes it renders correctly, but when it fails, the only error seems unrelated.
The fragment which appears blank when returning to it:
public class IpFragment extends Fragment implements ...{
private static final String TAG = "IpFragment";
private NavController navController;
private Context context;
private TextView tvIp;
#Nullable
#Override
public View onCreateView(#NonNull LayoutInflater inflater, #Nullable ViewGroup container, #Nullable Bundle savedInstanceState) {
navController = NavHostFragment.findNavController(this);
View v = inflater.inflate(R.layout.fragment_ip, container, false);
context = v.getContext();
return v;
}
#Override
public void onViewCreated(#NonNull View view, #Nullable Bundle savedInstanceState) {
super.onViewCreated(view, savedInstanceState);
Log.d(TAG, "onViewCreated");
ConnectivitySingleton.getInstance().registerCallback(this);
tvIp = view.findViewById(R.id.tvIp);
tvIp.setText(getDeviceIp());
}
#Override
public void onDestroyView() {
super.onDestroyView();
ConnectivitySingleton.getInstance().unregisterCallback(this);
}
...
}
The fragment we return from:
public class InterviewFragment extends Fragment implements ConnectionCallback, StreamStatusCallback, TextureView.SurfaceTextureListener, SpeakCallback {
private static final String TAG = "InterviewFragment";
private NavController navController;
private AutoFitDrawableView autoFitDrawableView;
private Context context;
public boolean isStreaming;
private MessageConnection messageConnection;
private TextView tvQuestion;
#Nullable
#Override
public View onCreateView(#NonNull LayoutInflater inflater, #Nullable ViewGroup container, #Nullable Bundle savedInstanceState) {
Log.d(TAG, "onCreateView");
// return super.onCreateView(inflater, container, savedInstanceState);
navController = NavHostFragment.findNavController(this);
View v = inflater.inflate(R.layout.fragment_interview, container, false);
context = v.getContext();
return v;
}
#Override
public void onViewCreated(#NonNull View view, #Nullable Bundle savedInstanceState) {
Log.d(TAG, "onViewCreated");
super.onViewCreated(view, savedInstanceState);
ConnectivitySingleton.getInstance().registerCallback(this);
VisionSingleton.getInstance().registerCallback(this);
SpeakSingleton.getInstance().registerCallback(this);
autoFitDrawableView = view.findViewById(R.id.autofit);
// need to set autoFitDrawableView's display size / rotation
int rotation = ((Activity) context).getWindowManager().getDefaultDisplay().getRotation();
autoFitDrawableView.setPreviewSizeAndRotation(800, 600, rotation); // w 800 h 600
// set listener to stream frames
autoFitDrawableView.setSurfaceTextureListenerForPreview(this);
tvQuestion = view.findViewById(R.id.question);
}
#Override
public void onDestroyView() {
Log.d(TAG, "onDestroyView");
super.onDestroyView();
ConnectivitySingleton.getInstance().unregisterCallback(this);
VisionSingleton.getInstance().unregisterCallback(this);
SpeakSingleton.getInstance().unregisterCallback(this);
}
#Override
public void onConnected() {
}
#Override
public void onDisconnected() {
navController.navigateUp();
}
#Override
/**
* Passes surfaceTexture to VisionSingleton once ST is available. VisionSingleton then sets up
* DTS camera to stream to surfaceTexture.
*/
public void onSurfaceTextureAvailable(SurfaceTexture surfaceTexture, int i, int i1) {
Log.d(TAG, "onSurfaceTextureAvailable");
VisionSingleton.getInstance().initPreview(surfaceTexture);
}
#Override
public void onSurfaceTextureSizeChanged(SurfaceTexture surfaceTexture, int i, int i1) { }
#Override
public boolean onSurfaceTextureDestroyed(SurfaceTexture surfaceTexture) {
Log.d(TAG, "onSurfaceTextureDestroyed");
VisionSingleton.getInstance().stopPreview();
return false;
}
#Override
/**
* If a 'vision start' command has been received, then surfaceTexture's frame should be sent to
* the phone app via messageConnection.
*/
public void onSurfaceTextureUpdated(SurfaceTexture surfaceTexture) {
if(isStreaming) {
try {
int tvWidth = autoFitDrawableView.getPreview().getWidth();
int tvHeight = autoFitDrawableView.getPreview().getHeight();
// Get bitmap from TextureView
Bitmap bm = Bitmap.createBitmap(tvWidth, tvHeight, Bitmap.Config.ARGB_8888);
autoFitDrawableView.getPreview().getBitmap(bm);
// Compress via JPG
ByteArrayOutputStream os = new ByteArrayOutputStream();
bm.compress(Bitmap.CompressFormat.JPEG, 50, os);
byte[] byteArray = os.toByteArray();
Log.d(TAG, "Byte size: " + byteArray.length);
if (byteArray.length > 1000000) {
Log.w(TAG, "Byte size is > 1 MB! Exceeds max sending size.");
} else {
messageConnection.sendMessage(new BufferMessage(byteArray));
}
} catch (Exception e) {
e.printStackTrace();
Log.e(TAG, e.getMessage());
}
}
}
#Override
public void onStartStream(final MessageConnection messageConnection) {
Log.d(TAG, "onStartStream");
isStreaming = true;
this.messageConnection = messageConnection;
}
#Override
public void onStopStream() {
Log.d(TAG, "onStopStream");
isStreaming = false;
}
#Override
public void onSpeakCommandReceived(String question) {
tvQuestion.setText(question);
}
}
Sometimes in InterviewFragment I get this caught error, which doesn't break anything at the time, but later when returning to IpFragment, it appears blank.
08-07 22:45:54.921 5196-5275/edu.unc.etlab.robojloomo W/MessageListener: Exception occured during command launch
android.view.ViewRootImpl$CalledFromWrongThreadException: Only the original thread that created a view hierarchy can touch its views.
at android.view.ViewRootImpl.checkThread(ViewRootImpl.java:6357)
at android.view.ViewRootImpl.requestLayout(ViewRootImpl.java:874)
at android.view.View.requestLayout(View.java:17476)
at android.view.View.requestLayout(View.java:17476)
at android.view.View.requestLayout(View.java:17476)
at android.view.View.requestLayout(View.java:17476)
at android.view.View.requestLayout(View.java:17476)
at android.view.View.requestLayout(View.java:17476)
at android.support.constraint.ConstraintLayout.requestLayout(ConstraintLayout.java:3172)
at android.view.View.requestLayout(View.java:17476)
at android.view.View.requestLayout(View.java:17476)
at android.widget.RelativeLayout.requestLayout(RelativeLayout.java:360)
at android.view.View.requestLayout(View.java:17476)
at android.widget.TextView.checkForRelayout(TextView.java:6865)
at android.widget.TextView.setText(TextView.java:4057)
at android.widget.TextView.setText(TextView.java:3915)
at android.widget.TextView.setText(TextView.java:3890)
at edu.unc.etlab.robojloomo.InterviewFragment.onSpeakCommandReceived(InterviewFragment.java:168)
at edu.unc.etlab.robojloomo.loomo_services.SpeakSingleton.speak(SpeakSingleton.java:69)
at edu.unc.etlab.robojloomo.listeners.SpeakCommand.execute(SpeakCommand.java:14)
at edu.unc.etlab.robojloomo.listeners.MessageListener.onMessageReceived(MessageListener.java:85)
at com.segway.robot.sdk.connectivity.RobotMessageConnection.handleMessage(RobotMessageConnection.java:219)
at android.os.Handler.dispatchMessage(Handler.java:98)
at android.os.Looper.loop(Looper.java:135)
at android.os.HandlerThread.run(HandlerThread.java:61)
This error happens when I set the text of a textView within InterviewFragment:
public void onSpeakCommandReceived(String question) {
tvQuestion.setText(question);
}
Ok, so quickly after posting this question I fixed it. I referred to this post to fix the error I was getting: Android "Only the original thread that created a view hierarchy can touch its views.". and I changed onSpeakCommandReceived() to:
public void onSpeakCommandReceived(final String question) {
getActivity().runOnUiThread(new Runnable() {
#Override
public void run() {
tvQuestion.setText(question);
}
});
}
Still not sure how this error caused the next screen to be blank, since they occur at different times, but now the error is fixed everything seems to work.

How to Text Recognize only detect inside overlay camera not all of camera size

I want to make ocr application that can recognize text, but I just want to detect text only inside rectangle.
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
// Inflate the layout for this fragment
View view = inflater.inflate(R.layout.fragment_transaksi, container, false);
cameraView = view.findViewById(R.id.surface_view);
txtView = view.findViewById(R.id.txtview);
mButton = view.findViewById(R.id.button1);
mButton.setOnClickListener(this);
txtRecognizer = new TextRecognizer.Builder(listener.getApplicationContext()).build();
detector = new FaceDetector.Builder(listener.getApplicationContext()).build();
cameraSource = new CameraSource.Builder(listener.getApplicationContext(), detector)
.setFacing(CameraSource.CAMERA_FACING_BACK)
.setRequestedPreviewSize(360 , 640)
.setRequestedFps(2.0f)
.setAutoFocusEnabled(true)
.build();
cameraView.getHolder().addCallback(this);
holder = cameraView.getHolder();
holder.addCallback((SurfaceHolder.Callback) this);
cameraView.setSecure(true);
transparentView = view.findViewById(R.id.transparent_view);
holderTransparent = transparentView.getHolder();
holderTransparent.addCallback((SurfaceHolder.Callback) this);
holderTransparent.setFormat(PixelFormat.TRANSLUCENT);
transparentView.setZOrderMediaOverlay(true);
deviceWidth=getScreenWidth();
deviceHeight=getScreenHeight();
return view;
}
public static int getScreenWidth() {
return Resources.getSystem().getDisplayMetrics().widthPixels;
}
public static int getScreenHeight() {
return Resources.getSystem().getDisplayMetrics().heightPixels;
}
private void Draw() {
Canvas canvas = holderTransparent.lockCanvas(null);
Paint paint = new Paint(Paint.ANTI_ALIAS_FLAG);
paint.setStyle(Paint.Style.STROKE);
paint.setColor(Color.GREEN);
paint.setStrokeWidth(3);
RectLeft = 40;
RectTop = 200 ;
RectRight = RectLeft+ deviceWidth-100;
RectBottom =RectTop+ 200;
Rect rec=new Rect((int) RectLeft,(int)RectTop,(int)RectRight,(int)RectBottom);
canvas.drawRect(rec,paint);
holderTransparent.unlockCanvasAndPost(canvas);
}
#Override
public void surfaceCreated(SurfaceHolder holder) {
try {
if (ActivityCompat.checkSelfPermission(listener,
Manifest.permission.CAMERA) != PackageManager.PERMISSION_GRANTED) {
ActivityCompat.requestPermissions(listener, new String[]{Manifest.permission.CAMERA},1);
return;
}
Draw();
cameraSource.start(cameraView.getHolder());
} catch (Exception e) {
e.printStackTrace();
}
}

One one fragment is updating the values

I'm basically getting a value updated inside an AsyncTask and I use onPostExecute to send it to the fragments.
All the fragments should display the same value on a TextView.
My problem is that my application has 3 fragment pages and only the middle page (Fragment_B) is updating...
(If I change Fragment_B to Fragment_A (in the line of code below), only Fragment_A will update).
public Fragment getItem(int position) {
switch (position)
{
case 0:
return new Fragmento_B();
case 1:
return new Fragmento_A(); //now only Fragment_A updates
case 2:
return new Fragmento_C();
default:
return null;
}
}
Why all the fragments don't update at the same time? The value is never displayed on Fragment_A and Fragment_C.
OnPostUpdate should update all the fragments but It only updates the Fragment_B. But I tried to debug this problem and I created a onPreUpdate and I SetText and it works for every fragments. I have no idea why this is happening. Can somebody help me?
public class Cliente extends AsyncTask<Void, Void, Void> {
String dstAddress;
int dstPort;
String[] valores = new String[2];
TextView textResponse,textResponse2;
public Cliente(String addr, int port, TextView textResponse) {
dstAddress = addr;
dstPort = port;
this.textResponse = textResponse;
// this.textResponse2 = textResponse2;
}
public Cliente(TextView textResponse) {
this.textResponse = textResponse;
}
#Override
protected void onPreExecute() {
super.onPreExecute();
textResponse.setText("HELLO");
}
#Override
protected Void doInBackground(Void... arg0) {
Socket socket = null;
try {
socket = new Socket(dstAddress, dstPort);
ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream(
1024);
byte[] buffer = new byte[1024];
int bytesRead;
Scanner r = new Scanner(new InputStreamReader(socket.getInputStream()));
/*
* notice: inputStream.read() will block if no data return
*/
valores[0] = r.nextLine();
} catch (UnknownHostException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} finally {
if (socket != null) {
try {
socket.close();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
return null;
}
#Override
protected void onPostExecute(Void result) {
super.onPostExecute(result);
textResponse.setText(":D");
}
Fragment A:
public View onCreateView(LayoutInflater inflater, #Nullable ViewGroup container, #Nullable Bundle savedInstanceState) {
View v = inflater.inflate(R.layout.activity_second,container,false);
x_atual = (TextView) v.findViewById(R.id.x_atual);
y_atual = (TextView) v.findViewById(R.id.y_atual);
x_desejado = (TextView) v.findViewById(R.id.x_desej);
y_desejado = (TextView) v.findViewById(R.id.y_desej);
ola = (TextView) v.findViewById(R.id.textView12);
new Cliente("192.168.2.5",6000,ola).execute();
return v;
}
Fragment B:
public class Fragmento_B extends android.support.v4.app.Fragment{
public TextView x_atual,y_atual,x_desejado,y_desejado,ola2,ola;
#Nullable
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
View v = inflater.inflate(R.layout.activity_third,container,false);
ola2 = (TextView) v.findViewById(R.id.textView2);
new Cliente("192.168.2.5",6000,ola2).execute();
return v;
}
Basically onPostUpdate only makes the ":D" appears on fragment_B and onPreUpdate works well and appears "Hello" on both.
FRAGMENTADAPTER ACTIVITY
public class Main2Activity extends FragmentActivity {
private TabLayout mTabLayout;
private ViewPager mViewPager;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main2);
mTabLayout = (TabLayout) findViewById(R.id.tab_layout);
mViewPager = (ViewPager) findViewById(R.id.view_pager);
mViewPager.setAdapter(new FragmentoAdapter(getSupportFragmentManager(),getResources().getStringArray(R.array.tiles_tab)));
mTabLayout.setupWithViewPager(mViewPager);
}
FRAGMENTADAPTER CLASS
public class FragmentoAdapter extends FragmentPagerAdapter {
private String[] mTabTiles;
public FragmentoAdapter(FragmentManager fm,String[] mTabTiles) {
super(fm);
this.mTabTiles = mTabTiles;
}
#Override
public Fragment getItem(int position) {
switch (position)
{
case 0:
return new Fragmento_A();
case 1:
return new Fragmento_B();
case 2:
return new Fragmento_C();
default:
return null;
}
}
#Override
public int getCount() {
return this.mTabTiles.length;
}
#Override
public int getItemPosition(Object object) {
return POSITION_NONE;
}
#Override
public CharSequence getPageTitle(int position) {
return this.mTabTiles[position];
}
}
MY APPLICATION

Fix Number Of Column And Row in Grid View

I am Listing all the Apps installed on device in Fragment which having gridview inside. what i want to do is, i want 4 col * 5 rows(20 App in one fragment only) , if i install new app (app count 21) it must set on the next fragment and set at the top left of new fragment , fragment should generate dynamically , and add to viewpager.
here is my code. MainActivity :
public class MainActivity extends FragmentActivity {
ViewPager pager;
AppViewAdapter adapter;
GridFrag gridFrag;
FragmentManager fragmentManager;
FragmentTransaction transaction;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
bindView();
init();
addListener();
}
private void bindView() {
pager = (ViewPager) findViewById(R.id.slideingpager);
}
private void init() {
adapter = new AppViewAdapter(getSupportFragmentManager());
pager.setAdapter(adapter);
}
}
GridFragment.java :
public class GridFrag extends android.support.v4.app.Fragment implements
OnItemClickListener {
GridView gridView;
ViewAdapter viewAdapter;
PackageManager packageManager;
int columnsOfGridView;
public class AppDetails {
Drawable icon;
String label;
}
AppDetails packages[];
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
return inflater.inflate(R.layout.gridfrag, container, false);
}
#Override
public void onActivityCreated(Bundle savedInstanceState) {
// TODO Auto-generated method stub
super.onActivityCreated(savedInstanceState);
packageManager = getActivity().getPackageManager();
gridView = (GridView) getActivity().findViewById(R.id.grid);
final Intent mainIntent = new Intent(Intent.ACTION_MAIN, null);
mainIntent.addCategory(Intent.CATEGORY_LAUNCHER);
List<ResolveInfo> packList = packageManager.queryIntentActivities(
mainIntent, 0);
packages = new AppDetails[packList.size()];
for (int i = 0; i < packList.size(); i++) {
packages[i] = new AppDetails();
packages[i].icon = packList.get(i).loadIcon(packageManager);
packages[i].label = packList.get(i).loadLabel(packageManager)
.toString();
}
viewAdapter = new ViewAdapter(getActivity(), packages);
gridView.setAdapter(viewAdapter);
int totalApps = gridView.getCount();
Toast.makeText(getActivity(), "Total "+ totalApps + " App(s)Found",Toast.LENGTH_SHORT).show();
gridView.setOnItemClickListener(this);
}
#Override
public void onItemClick(AdapterView<?> parent, View view, int position,
long id) {
// TODO Auto-generated method stub
Toast.makeText(getActivity(),
"You Clicked on : " + packages[position].label,
Toast.LENGTH_SHORT).show();
}
}
ViewAdapter.java (GridAdapter)
public class ViewAdapter extends BaseAdapter {
private Context context;
AppDetails setPacksForAdapter[];
public ViewAdapter(Context c, AppDetails apps[]) {
context = c;
setPacksForAdapter = apps;
}
#Override
public int getCount() {
// TODO Auto-generated method stub
return setPacksForAdapter.length;
}
#Override
public Object getItem(int arg0) {
// TODO Auto-generated method stub
return null;
}
#Override
public long getItemId(int arg0) {
// TODO Auto-generated method stub
return 0;
}
public static class ViewHolder {
ImageView imgDefaultAppIcon;
TextView tvDefaultAppLabel;
}
#Override
public View getView(int pos, View v, ViewGroup parent) {
// TODO Auto-generated method stub
ViewHolder holder = new ViewHolder();
if (v == null) {
LayoutInflater inflater = (LayoutInflater) context
.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
v = inflater.inflate(R.layout.grid_view, null);
holder.imgDefaultAppIcon = (ImageView) v
.findViewById(R.id.ivAppIcon);
holder.tvDefaultAppLabel = (TextView) v
.findViewById(R.id.tvAppLabel);
v.setTag(holder);
} else {
holder = (ViewHolder) v.getTag();
}
holder.imgDefaultAppIcon.setImageDrawable(setPacksForAdapter[pos].icon);
holder.tvDefaultAppLabel.setText(setPacksForAdapter[pos].label);
return v;
}
}
AppViewAdepter.java (For ViewPager)
public class AppViewAdapter extends FragmentPagerAdapter {
List<Fragment> fragmentsList;
public AppViewAdapter(FragmentManager fm) {
super(fm);
this.fragmentsList = new ArrayList<Fragment>();
for (int i = 0; i <= 2; i++) {
if (i % 2 == 0)
fragmentsList.add(new GridFrag());
else
fragmentsList.add(new FragTwo());
}
}
#Override
public Fragment getItem(int arg0) {
return fragmentsList.get(arg0);
}
#Override
public int getCount() {
// TODO Auto-generated method stub
return fragmentsList.size();
}
}
Set Layoutparams dynamically height of rootview of single grid in Adapter in getView() Method
(Device height / 5) - statusBarHieght
Some code : in getView() of Adapter
int grid_height = ((Helper.get_device_height(context)) / 5) - statusBarHeight;
GridView.LayoutParams layoutParams = (android.widget.AbsListView.LayoutParams) view.getLayoutParams();
layoutParams.height = grid_height;
view.setLayoutParams(layoutParams);
and,
gridview XML set columns=4
It will solve your problem.
Hope it will help you !
in your layout.xml by default <android:columnCount="auto_fit"> is set, you have to change it to as 4 by dong this <android:columnCount="4"> and to set rows similarly also in java you can do this like following setColumnCount(4) and setRowCount(5)

How to set onclick parallel with swipe in viewpager?

Here I have developed an app to view full screen images. I was able to develop it with swipe to move to next image. I have used a viewpager element.
How can I use onclick action to viewpager to do something.(delete, share etc..)
My code looks like below,
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_full_screen);
Thread child=new Thread(){
#Override
public void run() {
viewPager = (ViewPager) findViewById(R.id.pager);
utils = new Utils(getApplicationContext());
Intent i = getIntent();
int position = i.getIntExtra("position", 0);
adapter = new FullScreenImageAdapter(FullScreenViewActivity.this,utils.getFilePaths());
viewPager.setAdapter(adapter);
viewPager.setCurrentItem(position);//show the selected
btnMail=(Button)findViewById(R.id.btnMailThis);
btnRate=(Button)findViewById(R.id.btnRate);
btnMail.setVisibility(View.INVISIBLE);
btnRate.setVisibility(View.INVISIBLE);
}
};
child.start();
}
The FullScreenImageAdapter.java looks like below
public class FullScreenImageAdapter extends PagerAdapter {
private Activity _activity;
private ArrayList<String> _imagePaths;
private LayoutInflater inflater;
// constructor
public FullScreenImageAdapter(Activity activity,
ArrayList<String> imagePaths) {
this._activity = activity;
this._imagePaths = imagePaths;
}
#Override
public int getCount() {
return this._imagePaths.size();
}
#Override
public boolean isViewFromObject(View view, Object object) {
return view == ((RelativeLayout) object);
}
#Override
public Object instantiateItem(ViewGroup container, int position) {
TouchImageView imgDisplay;
//Button btnClose;
inflater = (LayoutInflater) _activity
.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
View viewLayout = inflater.inflate(R.layout.layout_full_image, container,
false);
imgDisplay = (TouchImageView) viewLayout.findViewById(R.id.imgDisplay);
//btnClose = (Button) viewLayout.findViewById(R.id.btnClose);
BitmapFactory.Options options = new BitmapFactory.Options();
options.inPreferredConfig = Bitmap.Config.ARGB_8888;
Bitmap bitmap = BitmapFactory.decodeFile(_imagePaths.get(position), options);
imgDisplay.setImageBitmap(bitmap);
/*
// close button click event
btnClose.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
_activity.finish();
}
});*/
((ViewPager) container).addView(viewLayout);
return viewLayout;
}
#Override
public void destroyItem(ViewGroup container, int position, Object object) {
((ViewPager) container).removeView((RelativeLayout) object);
}
Thanks in advance..!
You can create your own class inheriting ViewPager and override onInterceptTouchEvent like this:
#Override
public boolean onInterceptTouchEvent(MotionEvent arg0) {
// TODO Auto-generated method stub
if(arg0.getAction() == MotionEvent.ACTION_UP) {
//Your code here
return false;
} else {
//Do this to keep swipes working. It will also make vertical swiping work. You can avoid the latter by handling MotionEvent action and x,y directions.
return super.onInterceptTouchEvent(arg0);
}
}
Don't forget to replace the ViewPager object in your xml with com.example.yourpackagename.YourViewPagerClass

Categories

Resources